package com.bingbaihanji.springbooth2basedemo.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONWriter;
import com.bingbaihanji.springbooth2basedemo.pojo.Users;
import com.bingbaihanji.springbooth2basedemo.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 冰白寒祭
 * @date 2023-11-13 00:45:47
 * @description //TODO
 */

@RestController
@Slf4j
public class IndexController {

    @Resource
    private UserService userService;

    @GetMapping("/users")
    public List<Users> getListUsers() {
        List<Users> listUsers = userService.list();
        String jsonArrayString = JSONArray.toJSONString(listUsers, JSONWriter.Feature.PrettyFormat);
        log.info("\n" + jsonArrayString);
        return listUsers;
    }


    @GetMapping("/user/{id}")
    public Users getUserById(@PathVariable("id") Long id) {
        Users userById = userService.getById(id);
        System.out.println(userById);
        return userById;
    }


    //    {
    //        "age": 22,
    //            "email": "zhangchangyong@qq.com",
    //            "id" :"6",
    //            "name": "张长永"
    //    }
    @PostMapping("/users")
    public String insertUser(@RequestBody Users users) {
        int i = userService.getBaseMapper().insert(users);
        if (i != 0) {
            log.info("数据插入成功,数据表id为{}", users.getId());
            return "数据插入成功";
        } else {
            return "数据插入失败";
        }

    }

    @DeleteMapping("/user/{id}")
    public String deleteUserByMap(@PathVariable("id") Long id) {
        boolean i = userService.removeById(id);
        if (i) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @PutMapping("/users")
    public String updateUsersById(@RequestBody Users users) {
        boolean i = userService.updateById(users);
        if (i) {
            log.info("数据更新成功,数据表id为{}", users.getId());
            return "数据更新成功";
        } else {
            return "数据更新失败";
        }
    }

}
